/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * gestionarEntrega2.java
 *
 * Created on 01-may-2011, 11:00:47
 */

package interfaces.farmacia;


import Controlador.Controlador;
import Definiciones.Definiciones.Estado;
import GestorCitas.LineaReceta;
import GestorFarmacia.Lote;
import GestorFarmacia.Entrega;
import GestorFarmacia.Medicamento;
import GestorUsuarios.Usuario;
import clinica.ClinicaView;
import clinica.Interfaces;
import clinica.Interfaz;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jdesktop.application.Action;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Ana Ferreira Blanco
 */
public class gestionarEntrega2 extends javax.swing.JPanel {

    private ClinicaView app;
    private Interfaces anterior;
    private Entrega entrega;
    private Lote lote;
    private LineaReceta linea;
    private Medicamento medicament;
    private Usuario usuario;

    /** Creates new form gestionarEntrega2 */
    public gestionarEntrega2(ClinicaView a) {
        app = a;
        initComponents();
    }


    public void rellenaDatos(Entrega e, Usuario u,Interfaces ant)throws SQLException, IOException, ClassNotFoundException, ParseException, NoSuchAlgorithmException{
        DateFormat fecha_formato = new SimpleDateFormat("dd/MM/yyyy");
        Date fecha;
        Calendar fecha1;
        anterior = ant;
        entrega = e;
        linea =  entrega.getLineaReceta();
        Integer m = linea.getIdMedicamento();
        medicament = Medicamento.get(m);
        usuario = u;

        Integer dia,mes,anio,dia1,mes1,anio1;

        //Lotes asociados al medicamento de la entrega
        Lote[] lotes_asociados = medicament.getLotesMedicamento();
        if(lotes_asociados == null){
            app.abrirMensajeError("No se encontró ningún lote disponible para dicho medicamento.", anterior);
            return;
        }
        //Interesa gastar los que caduquen antes por tanto
        //Primero tomo los valore del primer lote obtenido
        Integer antiguo=lotes_asociados[0].getIdLote();
        Lote aux = Lote.get(antiguo);

        fecha = lotes_asociados[0].getFechaCaducidadLote();
        fecha1 = Calendar.getInstance();
        fecha1.setTime(fecha);

        dia1 = fecha1.get(Calendar.DAY_OF_MONTH);   //dia del mes
        mes1 = fecha1.get(Calendar.MONTH);  //mes, de 0 a 11
        anio1 = fecha1.get(Calendar.YEAR);  //año
        
        //Ahora recorro el resto de los lotes (si los hay) para encontrar el de fecha de caducidad más temprana
        if(lotes_asociados.length>1){
            for(Lote i:lotes_asociados){
               //Para cada lote transformo su fecha en Calendar y saco sus valores
               fecha = i.getFechaCaducidadLote();
               fecha1 = Calendar.getInstance();
               fecha1.setTime(fecha);
               dia = fecha1.get(Calendar.DAY_OF_MONTH);   //dia del mes
               mes = fecha1.get(Calendar.MONTH);  //mes, de 0 a 11
               anio = fecha1.get(Calendar.YEAR);
               //compruebo el año
               if(anio<anio1)
                    antiguo = i.getIdLote();
               else if (anio == anio1){ //A igualdad de año, compruebo el mes
                    if(mes<mes1)
                        antiguo = i.getIdLote();
                    else if (mes == mes1){ //A igualdad de mes, compruebo el dia
                        if(dia<dia1)
                            antiguo = i.getIdLote();
                        else if (dia == dia1){ //A igualdad de dia, compruebo el stock disponible
                            if(i.getUnidadesRestantesLote()<aux.getUnidadesRestantesLote())
                                antiguo = i.getIdLote();

                        }
                    }
               }
            }
        }

        //Información del lote
        lote=Lote.get(antiguo);
        codigo.setText(lote.getIdLote().toString());
        caducidad.setText(fecha_formato.format(lote.getFechaCaducidadLote()));
        medicamento.setText(medicament.getNombreMedicamento());
        //Información del paciente
        paciente.setText(u.getNombre()+ " " + u.getApellidos());
        dni.setText(u.getDniPasaporte());
        
    }

    @Action
    public void cancelar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException, ParseException {
        app.abrirGestionarEntrega(usuario,anterior);
    }

    @Action
    public void aceptar() throws NoSuchAlgorithmException, IOException, ClassNotFoundException, SQLException, ParseException {
        //Obtengo el farmacéutico que está realizando la entrega
        Usuario f = Controlador.getUsuarioActivo();
        Integer id_f = f.getIdUsuario();
        //Cambiar estado de la entrega y Asignar farmacéutico
        String res = Controlador.gestionarEstadoEntrega(entrega.getIdEntrega(), Estado.SUMINISTRADA);

        //Asigno el farmacéutico a la entrega
        entrega.setIdFarmaceutico(id_f);

        //Actualizar stock
        Integer actual =  lote.getUnidadesRestantesLote();
        Controlador.modificarLote(lote.getIdLote(), null, null, null,null, actual-1,null);

        if(res==null){
            app.abrirMensajeExito("La entrega se ha registrado como Suministrada", Interfaces.PRINCIPAL_FARMACEUTICO);
        }
         else{
            app.abrirMensajeError(res, Interfaces.PRINCIPAL_FARMACEUTICO);
         }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        codigo = new javax.swing.JTextField();
        caducidad = new javax.swing.JTextField();
        medicamento = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        paciente = new javax.swing.JTextField();
        dni = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Confirme la entrega", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel1.setName("jPanel1"); // NOI18N
        jPanel1.setPreferredSize(new java.awt.Dimension(1147, 470));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Información del Lote", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel2.setName("jPanel2"); // NOI18N

        jLabel1.setFont(Interfaz.setFontSize());
        jLabel1.setText("Fecha caducidad:");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel3.setFont(Interfaz.setFontSize());
        jLabel3.setText("Medicamento:");
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel2.setFont(Interfaz.setFontSize());
        jLabel2.setText("Código:");
        jLabel2.setName("jLabel2"); // NOI18N

        codigo.setEditable(false);
        codigo.setFont(Interfaz.setFontSize());
        codigo.setName("codigo"); // NOI18N

        caducidad.setEditable(false);
        caducidad.setFont(Interfaz.setFontSize());
        caducidad.setName("caducidad"); // NOI18N

        medicamento.setEditable(false);
        medicamento.setFont(Interfaz.setFontSize());
        medicamento.setName("medicamento"); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(116, 116, 116)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(caducidad, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
                    .addComponent(medicamento, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
                    .addComponent(codigo, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(caducidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(11, 11, 11)
                        .addComponent(medicamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Información del paciente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, Interfaz.setFontSize()));
        jPanel3.setName("jPanel3"); // NOI18N

        jLabel4.setFont(Interfaz.setFontSize());
        jLabel4.setText("Nombre:");
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setFont(Interfaz.setFontSize());
        jLabel5.setText("DNI:");
        jLabel5.setName("jLabel5"); // NOI18N

        paciente.setEditable(false);
        paciente.setFont(Interfaz.setFontSize());
        paciente.setToolTipText("");
        paciente.setName("paciente"); // NOI18N

        dni.setEditable(false);
        dni.setFont(Interfaz.setFontSize());
        dni.setName("dni"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(183, 183, 183)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dni, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE)
                    .addComponent(paciente, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(paciente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(20, 20, 20))
        );

        paciente.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance().getContext().getActionMap(gestionarEntrega2.class, this);
        jButton2.setAction(actionMap.get("cancelar")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(gestionarEntrega2.class);
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setLabel(resourceMap.getString("jButton2.label")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        jButton1.setAction(actionMap.get("aceptar")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setLabel(resourceMap.getString("jButton2.label")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 756, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(13, 13, 13))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField caducidad;
    private javax.swing.JTextField codigo;
    private javax.swing.JTextField dni;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField medicamento;
    private javax.swing.JTextField paciente;
    // End of variables declaration//GEN-END:variables

}
